package com.hnluchuan.bmjlearning.web.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.hnluchuan.bmjlearning.common.ResultCode;
import com.hnluchuan.bmjlearning.common.SmsTemplateType;
import com.hnluchuan.bmjlearning.common.UserType;
import com.hnluchuan.bmjlearning.dto.AgentDTO;
import com.hnluchuan.bmjlearning.dto.CustomerDTO;
import com.hnluchuan.bmjlearning.dto.MenuDTO;
import com.hnluchuan.bmjlearning.dto.RoleMenuDTO;
import com.hnluchuan.bmjlearning.dto.SmsDTO;
import com.hnluchuan.bmjlearning.dto.UserDTO;
import com.hnluchuan.bmjlearning.enums.SmsType;
import com.hnluchuan.bmjlearning.model.Menu;
import com.hnluchuan.bmjlearning.model.Role;
import com.hnluchuan.bmjlearning.model.Sms;
import com.hnluchuan.bmjlearning.service.MenuService;
import com.hnluchuan.utils.exception.BizException;

@Controller
public class IndexController extends BaseController {

	@Autowired
	private MenuService menuService;

	private Integer verCodeLength = 6;
	
    @RequestMapping(value = "/index")
    public String index(Map<String, Object> map) {    
    	return "redirect:/admin/index";
    }
    
	@RequestMapping(value = "/admin/index")
	public String adminIndex(Map<String, Object> map) {

		MenuDTO rootMenu = menuService.listForAdminPage();
		List<Role> roles = userRoleService.findRolesByUserId(getCurrentUserDTO().getId());
		List<RoleMenuDTO> roleMenuDTOs = new ArrayList<>();
		for (Role role : roles) {
			roleMenuDTOs.addAll(roleMenuService.findByRole(role.getId()));
		}
		for (Menu l1 : rootMenu.getChildren()) { // l1是一级菜单
			boolean none = true;
			for (Menu l2 : l1.getChildren()) { // l2是二级菜单
				if (!l2.getShow()) { // 不显示
					continue;
				}
				boolean show = ifContains(roleMenuDTOs, l2.getId());
				l2.setShow(show);
				if (show) {
					none = false;
				}
			}
			if (none) {
				l1.setShow(false);
			} else {
				l1.setShow(true);
			}
		}

		UserDTO currentUser = getCurrentUserDTO();
		if(currentUser.getType() == UserType.Agent.getValue()) {
			AgentDTO agentDTO = agentService.findByUserId(currentUser.getId());
			int customerCount = agentDTO.getCustomers();
			int newlyEnrolledCount = customerService.getTodayNewlyEnrolledCustomersCount(agentDTO.getId());
			int remainPackageCount = agentServicePackageService.getValidServicePackageCount(currentUser.getId(), null).intValue();

			map.put("customerCount", customerCount);
			map.put("newlyEnrolledCount", newlyEnrolledCount);
			map.put("remainPackageCount", remainPackageCount);
		}else if(currentUser.getType() == UserType.Clinic.getValue()){
			CustomerDTO customerDTO = customerService.findByUserId(currentUser.getId());
			Date expiredDate = customerDTO.getExpireDate();
			Date now = new Date();
			Long days = 0l;
			if (expiredDate != null) {
				days = getDateDiff(now, expiredDate, TimeUnit.DAYS);
				days = days < 0 ? 0 : days;
			}
			map.put("expiredDate", expiredDate);
			map.put("restDays", days);
		}
		map.put("rootMenu", rootMenu);
		map.put("user", currentUser);
		if (currentUser.getType() == UserType.Agent.getValue()) {
			map.put("agent", getCurrentAgentDTO());
		} else if (currentUser.getType() == UserType.Clinic.getValue()) {
			map.put("clinic", getCurrentClinicDTO());
		}
		return "admin/index";
	}
	
	private boolean ifContains(List<RoleMenuDTO> roleMenuDTOs, Long id) {
		for (RoleMenuDTO rm : roleMenuDTOs) {
			if (rm.getMenu().getId().longValue() == id) {
				return true;
			}
		}
		return false;
	}
	
	@RequestMapping(value = "/admin/login")
	public String adminLogin(@CookieValue(value = "remember-me", defaultValue = "") String rememberMe,  Map<String, Object> map) {
		if (StringUtils.isNotBlank(rememberMe)) {
			return "redirect:/admin/index";
		}
	    if (new File("/Users/kevin/code").exists()) {
	        map.put("self", true);
	    }
		return "admin/login";
	}

	@RequestMapping(value = "/admin/5thhospital")
	public String adminLogin5thhospital(@CookieValue(value = "remember-me", defaultValue = "") String rememberMe,  Map<String, Object> map) {
		if (StringUtils.isNotBlank(rememberMe)) {
			return "redirect:/admin/index";
		}
		if (new File("/Users/kevin/code").exists()) {
			map.put("self", true);
		}
		return "admin/5thhospital";
	}


	@RequestMapping(value = "/admin/forgetPwd")
	public String forgetPwd(Map<String, Object> map) {
		return "admin/forgetPwd";
	}

	/**
	 *发送验证码
	 * */
	@Transactional
	@ResponseBody
	@RequestMapping(value = "/admin/sendSmsVCode" , produces="text/html;charset=UTF-8")
	public String sendVerCode( Map<String, Object> map, String phone) throws ClientException {
	    //required(phoneNumber, ResultCode.PhoneNumError.getRemark());
	    if (StringUtils.isBlank(phone)) {
            throw new BizException( ResultCode.PhoneNumError.getRemark());
        }
		String smsVerCode = smsService.getRandNum(verCodeLength);
		Date now = new Date();
		//用户表是否有此号码
		UserDTO query = new UserDTO();
		query.setUsername(phone);
		UserDTO u = userService.findOne(query);
		if (u != null) {
			//如果有此手机号，则判断上一次发短信时间是否在5分钟内，在则不重新发送
			Sms historySms = smsService.findByExpireDate(now);
			if (historySms == null){
				SendSmsResponse sendSmsResponse = smsService.sendSms(phone, SmsTemplateType.ModifyPassword, smsVerCode);
				if (sendSmsResponse.getCode().equals("OK")) {
                    SmsDTO dto = new SmsDTO();
                    dto.setCreated(now);
                    dto.setCode(smsVerCode);
                    dto.setExpireDate(addMinute(now, 5));
                    dto.setMobile(phone);
                    dto.setType(SmsType.Type1.getValue());
                    dto.setMsg(sendSmsResponse.getMessage());
                    dto.setUsed(false);
                    smsService.create(dto);
                } else {
                    throw new BizException( sendSmsResponse.getMessage());
                }
			} else {
			    throw new BizException(ResultCode.GetVerCodeError.getRemark());
			}
		}else {
			throw new BizException(ResultCode.UserNotExist.getRemark());
		}
		return ok();
	}

	/**
	 * 忘记密码 通过手机验证码 修改密码
	 * */
	@ResponseBody
	@Transactional
	@RequestMapping(value = "/admin/modifyPassword" , produces="text/html;charset=UTF-8")
	public String modifyPassword(String password, String phone, String code ) {
	    //某号码五分钟内的短信
		Sms sms = smsService.findLastOneByMobile(phone, code);
		UserDTO user = userService.loadUserByUsername(phone);
		if (sms == null) {
			throw new BizException(ResultCode.VerCodeError.getRemark());
		} else {
			if (sms.getUsed()) {
                throw new BizException(ResultCode.InvalidVerCodeError.getRemark());
			} else {
                if (user.getId()!= null) {
                    userService.resetPassword(password,user.getId());
                    sms.setUsed(true);
                    return ok();
                }
			}
		}
		return ok("unknow");
	}


}	
